package com.cilico.single.view;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.cilico.single.R;
import com.cilico.single.components.Alert;
import com.cilico.single.components.Component;
import com.cilico.single.components.Radio;
import com.cilico.single.components.RowPanel;
import com.cilico.single.components.Select;
import com.cilico.single.components.TabBar;
import com.cilico.single.components.TabBar.ContentLayout;
import com.cilico.single.components.Table;
import com.cilico.single.components.Table.Cell;
import com.cilico.single.components.cCheckBox;
import com.cilico.single.components.mButton;
import com.cilico.single.components.mTextField;
import com.cilico.single.utils.PackageManagerAndroid;
import com.cilico.single.utils.Utils;
import com.cilico.single.waterfall.ImageUtil;

/**
 * 常用控制类
 * @author lv.xiangan
 *
 */
public class GeneralController {


	public static boolean disposeButtonEvent(View component, BaseView bv) {
        mButton btn = (mButton) component;
        String name = btn.attrName_;
        if (name != null) {
            // 用户点击“退出”按钮则直接退出系统
            if (name.equalsIgnoreCase("ewp_close_app")) {
            	Alert.exitSystem(bv);
                return true;
            } else if(name.equalsIgnoreCase("allCheck")||name.equalsIgnoreCase("allCancel")){
            	// 点击全选/全部取消
            	Boolean IsCheck=false;
            	if(name.equalsIgnoreCase("allCheck")){
            		IsCheck=true;
            	}
            	if(name.equalsIgnoreCase("allCancel")){
            		IsCheck=false;
            	}
            			
                View view;
                // 获取中间layout的控件总数
                int sizeMid = bv.tabBar_.getContentChildCount();
                // 遍历控件
                for (int i = 0; i < sizeMid; i++) {
                	   view = bv.tabBar_.getContentChild(i);
                       if (view instanceof FormLayout) {
                           FormLayout fl = (FormLayout) view;
                           int sizeForm = fl.getChildCount();
                           for (int n = 0; n < sizeForm; n++) {
                        	   view = fl.getChildAt(n);
                        	   if (view instanceof Table) {
                        		   Table tableView = (Table)view;
                        		   int tableChildCount = tableView.getChildCount();
                        		   for (int cn = 0; cn < tableChildCount; cn ++) {
                        			   View v = tableView.getChildAt(cn);
                        			   if (v instanceof Table.Cell.CellLayout){
                        				  View vvv = ((Table.Cell.CellLayout) v).getChildAt(0);
                        				  RowPanel rowPanel = (RowPanel)vvv;
                        				   if(rowPanel.getChildAt(0) instanceof cCheckBox){
                        					  cCheckBox checkboxView =  (cCheckBox) rowPanel.getChildAt(0);
                        					  
                        					  checkboxView.setChecked(IsCheck); 
                                			  bv.tabBar_.invalidate();
                        				  }
                        				 
                            		   }
                        		   }
                               }
                           }
                       }
                }
            	return true;
            } else if (name.equalsIgnoreCase("logout")) {
				//用户退出登录
            	final String userName = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.USER_NAME);
            	final String id_RESTAURANT = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.RESTAURANT_USER_ID);
            	if (userName == null || id_RESTAURANT == null 
            			|| userName.equals("") || id_RESTAURANT.equals("")) {
            		Toast.makeText(bv, "当前没有用户登录", Toast.LENGTH_LONG).show();
				}else {
					AlertDialog.Builder builder = new Builder(bv);
					builder.setTitle("警告信息！");
					builder.setMessage("您确定退出当前用户的登录吗？");
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.USER_NAME, "");
			            	BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.RESTAURANT_USER_ID, "");
						}
					});
					builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							
						}
					});
					builder.create().show();
				}
            	
			}else if (name.equalsIgnoreCase("clearcach")) {//系统优化
				ImageUtil.clearPicture(bv);
				return true;
			}
        }
        if (null != btn.buttonType_ && btn.buttonType_.equalsIgnoreCase("button")) {
            try {
                if (btn.attrName_ != null && btn.attrName_.equals("ewp_relogin")) {
                    // 该判断由于服务端为将就已上线测试的iphone，将按钮类型由原来的submit改成了button
                    FormAction faction = bv.getFormByComponent(component);
                    if (faction != null) {
                        faction.PostForm((mButton) component, bv);
                    }
                } else if (btn.attrName_ != null && btn.attrName_.equalsIgnoreCase("system")) {
					//服务员版本，系统设置
                	Intent intent = new Intent();
                	intent.setClass(bv, SysSeting.class);
    				bv.startActivity(intent);
				}else {
                    disposeNormalButton(bv, btn);
                }
            } catch (Exception e) {
                Utils.printException(e);
            }
        } else {
            // We'll submit some infor to the server or reset the form.
            FormAction faction = bv.getFormByComponent(component);
            if (faction != null) {
                faction.PostForm((mButton) component, bv);
            }
        }
        return true;
    }

    /**
     * If the button type is "button", it means the disposing is local without connecting to the net.
     * 
     * @param bv
     * @param btn
     * @throws Exception
     */
    protected static void disposeNormalButton(BaseView bv, mButton btn) throws Exception {
        if (bv == null || btn == null) {
            return;
        }
        // Create/find the layout related to the button.
        ContentLayout layout = null;
        layout = bv.createLocalLayout(btn.accessory_, bv);
        if (layout != null) {
            Table table = BaseView.searchTableInSameDiv(btn);
            layout.parentTable_ = table;
        }
        /* dispose the button action with found ViewGroup. */
        if (btn.buttonAction_ == null) {
            if (btn.accessory_ != null) {
                if (layout != null) {
                    // means the button leads to jump to the accessory URI.
                    GeneralController.jumpToView(bv, layout, true);
                    bv.isInCeAirCjrLxrDiv_ = true;
                } else {
                    bv.dealWithLink(btn.accessory_, bv, false);
                }
            }
            // 处理加减联动控件内容
            if (null != btn.linkage_) {
            	dealWithLinkage(bv, btn);
            }
        } else {
            if (btn.buttonAction_.equalsIgnoreCase(mButton.BTN_ACT_ADD)) {
                disposeBtnActAdd(bv, btn.accessory_, layout);
            } else if (btn.buttonAction_.equalsIgnoreCase(mButton.BTN_ACT_DEL)) {
                disposeBtnActDel(bv, btn.accessory_, layout);
            } else if (btn.buttonAction_.equalsIgnoreCase(mButton.BTN_ACT_CONFIRM)) {
                switchScreen(bv, btn);
            } else if (btn.buttonAction_.equalsIgnoreCase("update")) {
                updateTable(bv, btn);
            }
        }
    }

    /**
     * 处理加减按钮联动输入框内容
     * @param bv
     * @param btn
     */
	private static void dealWithLinkage(BaseView bv, mButton btn) {
		try {
			int size = bv.vWidgetArray_.size();
			for (int i = 0; i < size; i++) {
				Object o = bv.vWidgetArray_.elementAt(i);
				if (o instanceof mTextField) {
					mTextField tf = (mTextField) o;
					String textValue = tf.getText().toString();
					if (btn.linkage_.equals(tf.attrName_) && null != textValue) {
						if (btn.linkType_.equalsIgnoreCase("plus")) {
							// 点击“加号”
							int val = Integer.parseInt(textValue);
							int maxVal = Integer.parseInt(btn.maxValue_);
							if (val < maxVal) {
								val++;
								tf.setText(String.valueOf(val));
							}
						} else if (btn.linkType_.equalsIgnoreCase("minus")) {
							// 点击“减号”
							int val = Integer.parseInt(textValue);
							int minVal = Integer.parseInt(btn.minValue_);
							if (val > minVal) {
								val--;
								tf.setText(String.valueOf(val));
							}
						}
					}
				}
			}
		} catch (Exception e) {
			Utils.printOutToConsole(e.getMessage());
		}
	}
    
    /**
     * Dispose button action "add".
     * 
     * @param bv
     * @param accessory
     * @param layout
     */
    private static void disposeBtnActAdd(BaseView bv, String accessory, ContentLayout layout) {
        if (bv == null) {
            return;
        }
        if (accessory == null || !accessory.startsWith("cusv_add://")) {
            return;
        }
        GeneralController.jumpToView(bv, layout, true);
    }

    /**
     * @param bv
     * @param accessory
     * @param layout
     */
    private static void disposeBtnActDel(BaseView bv, String accessory, ContentLayout layout) {
        // TODO Auto-generated method stub
    }

    /**
     * @param bv
     * @param cmp
     */
    private static void switchScreen(BaseView bv, Component cmp) throws Exception {
        if (cmp == null || bv == null) {
            return;
        }
        // get the view to confirm back the data.
        View backView = bv.popContentStack();
        if (backView == null) {
            return;
        }

        // TODO Take back the data.
        /* get the table in scroll views. */
        View currentView = bv.tabBar_.getContentLayout();
        if (currentView == null || !(currentView instanceof ContentLayout)) {
            return;
        }
        Table parentTable = ((ContentLayout) currentView).parentTable_;
        // get a previous cell for its CSS styles.
        Cell oldCell = parentTable.cells_.elementAt(0);
        /* replace cells of parent table. */
        // create new cells.
        ArrayList<Table.Cell> neoCells = new ArrayList<Table.Cell>();
        // get the table within the button.
        Table currentTable = Table.findTable(cmp.getCmpView());
        // if only ONE data should be taken back.
        boolean isCheckOne = false;
        if (currentTable != null) {
            // confirm the components in the same row of the Button.
            isCheckOne = true;
        } else {
            // confirm all checked components in the page.
            isCheckOne = false;
            currentTable = BaseView.searchTableInSameDiv(cmp.getCmpView());
        }
        ArrayList<Component> views = null;
        if (isCheckOne) {
            views = Table.findSameRowComponents(currentTable, cmp);
        } else {
            views = currentTable.getAllViews();
        }
        /* create a new cells. */
        int row = 0;
        String hiddenValue = "";
        for (int i = 0; i < views.size(); i++) {
            Table.Cell cell = null;
            // get backValue.
            Component c = views.get(i);
            if (c == null) {
                continue;
            }
            if (c instanceof cCheckBox) {
                cCheckBox checkBox = (cCheckBox) c;
                if (checkBox.backValue_ == null) {
                    continue;
                }
                if (!isCheckOne && !checkBox.isChecked()) {
                    // do NOT create cell for it has not been checked.
                    continue;
                }
                String backValue = checkBox.backValue_;
                cell = Table.createCell(backValue, oldCell, bv, row, 0);
                if (cell != null) {
                    neoCells.add(cell);
                    row++;
                    // 将用户选择的多选项按照“name=value&”格式组成字符串
                    hiddenValue = hiddenValue.concat(checkBox.attrName_).concat("=").concat(checkBox.attrValue_).concat("&");
                }
            } else if (c instanceof Radio) {
                Radio radio = (Radio) c;
                if (radio.backValue_ == null) {
                    continue;
                }
                if (!isCheckOne && !radio.isChecked()) {
                    // do NOT create cell for it has not been checked.
                    continue;
                }
                String backValue = radio.backValue_;
                cell = Table.createCell(backValue, oldCell, bv, row, 0);
                if (cell != null) {
                    neoCells.add(cell);
                    row++;
                    // 将用户选择的多选项按照“name=value&”格式组成字符串
                    hiddenValue = hiddenValue.concat(radio.attrName_).concat("=").concat(radio.attrValue_).concat("&");
                }
            }
        }
        // 将用户选择的多个乘机人数据添加至hidden_变量

        FormAction fa = bv.getFormByComponent(parentTable);
        fa.hidden_ = Utils.replaceString(fa.hidden_, hiddenValue);

        if (neoCells.size() < 1) {
            // It means that no one has been checked.
            BaseView.mid_.alert(bv, bv.getString(R.string.alert_select_cjr), false);
            bv.pushContentStack(backView);
            return;
        }
        // replace the parent table with the new table.
        Table neotable = new Table(bv);
        neotable.copyAttribute(parentTable);
        for (Table.Cell cell : neoCells) {
            if (cell == null) {
                continue;
            }
            neotable.addCell(cell);
        }
        // LPParseHtml.applyCssOnLayout(neotable, parentTable.cssStyle_);
        neotable.setCssStyle(parentTable.cssStyle_);
        neotable.mould();
        ViewGroup vg = (ViewGroup) parentTable.getParent();
        int index = vg.indexOfChild(parentTable);
        vg.removeViewAt(index);
        vg.addView(neotable, index);
        try {
            ((Component) vg).mould();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
        /* go back to the last view. */
        GeneralController.jumpToView(bv, backView, false);

        int indexInForm = fa.itemV_.indexOf(parentTable);
        fa.itemV_.remove(indexInForm);
        fa.itemV_.insertElementAt(neotable, indexInForm);
        if (bv.isContentStackEmpty()) {
            bv.isInCeAirCjrLxrDiv_ = false;
        }
    }

    /**
     * 更新table
     * 
     * @param bv
     * @param btn
     * 
     */
    private static void updateTable(BaseView bv, mButton btn) {
        int elementCount = bv.tabBar_.getContentChildCount();
        for (int i = 0; i < elementCount; i++) {
            View view = bv.tabBar_.getContentChild(i);
            if (view instanceof Table) {
                Table table = (Table) view;
                if (table.getTag().equals(btn.getTag())) {
                    Table.isUpdateTable_ = i;
                    bv.tabBar_.removeContentChild(i);
                    // ((TestCssStyle)bv).parse(R.raw.testxml);//此处换成网络获取即可
                    break;
                }
            }
        }
        Table.isUpdateTable_ = -1;
    }

    /**
     * @param component
     * @param bv
     * @return
     */
    public static boolean disposeTableEvent(View component, BaseView bv) {
        Table table = (Table) component;
        String accessory = Table.getCurrentAccessory(table);
        String addendum = Table.getCurrentAddendum(table);
        if (addendum != null) {
        	StringBuffer addStr = new StringBuffer();
        	if (addendum.equalsIgnoreCase("gps")) {}
        	accessory = accessory.concat(addStr.toString());
        }
        if (accessory == null) {
            return false;
        }
        if (accessory.startsWith("cusv_select://")) {
            Select select = Table.findSelect(table, accessory);
            if (select != null) {
                if (!Select.ISRUNNING) {
                    Select.ISRUNNING = true;
                    Select.TouchWidthAccessory(bv, select, accessory);
                }
            }
        } else if (accessory.startsWith("inclu_select://")) {
			String selectName = accessory.substring("inclu_select://".length());
			Select select = Table.findSelect(table, selectName);
			if (select != null) {
				int keyCode = KeyEvent.KEYCODE_DPAD_CENTER;
				KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
				select.requestFocus();
				select.onKeyDown(keyCode, event);
			}
		
        } else if (accessory.startsWith("name://")) {
            // Create/find the layout related to the button.
            TabBar.ContentLayout layout = null;
            layout = bv.createLocalLayout(accessory, bv);
            /* dispose the button action with found ViewGroup. */
            if (layout != null) {
                // means the button leads to jump to the accessory URI.
                jumpToView(bv, layout, true);
            }
        } else if (accessory.startsWith("alert://")) {
            Builder ad = new AlertDialog.Builder(bv);
            /**
             * ----------------------------------------------------------------
             * 由于服务端传过来的数据有可能存在较少的情况，这样弹出来的警告框宽度回不足，下面的确定按钮会被压缩，或者确定两字会竖向排列， 所以如果字数不足则在后面补充空格填充。
             */
            String temp = accessory.substring("alert://".length());
            if (temp.length() < 15) {
                temp = temp.concat("        ");
            }
            /**
             * ----------------------------------------------------------------
             */
            ad.setMessage(temp).setPositiveButton("确定", new OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }

            });
            if (!bv.isFinishing()) {
                ad.show();
            }
        } else {
            if (accessory.indexOf("reg_notice") != -1) {
                // 如果用户要查看注册的客户须知，则保持用户输入的注册数据
                FormAction faction = bv.getFormByComponent(component);
                faction.saveRegistDataToPropertyTemp(bv);
            }
            if (accessory.indexOf("/getui") != -1) {
            	String url = accessory.replace("lp://", "http://");
    			try {
					BaseView.mid_.um_.switchUIVIew(bv, url, "mbk_info_switching");
				} catch (Exception e) {
					Utils.printException(e);
				}
            } else{
            	if (table.form != null) {
					int tableChildCount = table.getChildCount();
					for (int cn = 0; cn < tableChildCount; cn++) {
						View v = table.getChildAt(cn);
						if (v instanceof Table.Cell.CellLayout) {
							View vvv = ((Table.Cell.CellLayout) v).getChildAt(0);
							RowPanel rowPanel = (RowPanel) vvv;
							if (rowPanel.getChildAt(0) instanceof Select){
								Select select = (Select) rowPanel.getChildAt(0);
								if (select.form_ != null) {
									String value = select.dropdownMenuText_.elementAt(select.currentMenu_).value_;
									accessory = accessory.concat("&"+select.selectName_+"="+value);
								}
							}
						}
					}
				}
                bv.dealWithLink(accessory, bv, false);
            }
        }
        return true;
    }

    /**
     * @param bv
     * @param destView
     * @param restoreCurrentLayout
     */
    public static void jumpToView(final BaseView bv, View destView, boolean restoreCurrentLayout) {
        if (bv == null) {
            return;
        }

        bv.resetMiddlePanel(destView, restoreCurrentLayout);
        if (bv instanceof LoginView) {
            bv.setLeftMenuMode(BaseView.BACK_MENU);
            if (null != BaseView.leftMenuText_) {
                bv.titleBar_.showBack_ = true;
                bv.titleBar_.backText_ = BaseView.leftMenuText_;
            }
        }
        bv.refresh();
        new Timer().schedule(new TimerTask() {

            public void run() {
                // 重新调整一下整个界面的联动显示效果
                // 暂时的处理方法是将联动延迟300毫秒。由于在联动里面有个判断条件，控件可见才参加联动，
                // 由于线程问题该界面有个下拉框控件没有正确参与到联动，所以进行了300毫秒的延时操作让他能正确参与联动。
                Utils.settleComponets(bv);
            }

        }, 300);

        bv.refresh();
    }
    
}

